package com.xmler.plugin.adbrocket.adb.command

import com.android.ddmlib.IDevice
import com.android.tools.idea.run.activity.ActivityLocator
import com.android.tools.idea.run.activity.DefaultActivityLocator
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ThrowableComputable
import com.xmler.plugin.adbrocket.adb.command.receiver.DisplayReceiver
import com.xmler.plugin.adbrocket.utils.Logger
import org.jetbrains.android.facet.AndroidFacet
import java.util.concurrent.TimeUnit
import javax.swing.JTextArea

class StartDefaultActivityCmd : ICommand {
    override fun run(project: Project, device: IDevice, facet: AndroidFacet, packageName: String, display: JTextArea): Boolean {
        try {

            val activity = getDefaultActivity(facet, device)
            val cmd = "am start -n $packageName/$activity"
            val receiver = DisplayReceiver(display)
            device.executeShellCommand(cmd, receiver, 10L, TimeUnit.SECONDS)
            if (receiver.isSuccess) {
                Logger.d("%s started on %s", packageName, device.name)
                return true
            } else {
                Logger.d("%s could not be started on %s", packageName, device.name)
            }
        } catch (e: Exception) {
            Logger.e("Start fail... ${e.message}")
        }
        return false
    }

    private fun getDefaultActivity(facet: AndroidFacet, device: IDevice): String {
        return ApplicationManager.getApplication().runReadAction(ThrowableComputable<String, ActivityLocator.ActivityLocatorException?>{
            DefaultActivityLocator(facet).getQualifiedActivityName(device)
        })
    }

}
